package com.baichuan.exception;

import com.baichuan.util.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;


/**
 * @Auther: leo
 * @Date: 2020/3/27 13:53
 * @Description: 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * @param request
     * @param e
     * @return
     * @author zhyong
     * @date 2020/03/16 09:36
     * @description：404处理
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String notFountHandler(HttpServletRequest request, NoHandlerFoundException e) {
        String method = request.getMethod();
        String path = request.getRequestURI();
        log.info("not found request path:{},method:{}", path, method, e);
        return ResponseResult.writeFail404();
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public String errorHandler(HttpServletRequest request, Exception e) {
        String method = request.getMethod();
        String path = request.getRequestURI();
        log.error("request error path:{},method:{}", path, method, e);
        return ResponseResult.writeServerError();
    }
}
